package com.vrv.im.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vrv.im.domain.UserBean;
import com.vrv.im.persistence.UserMapper;
import com.vrv.im.service.UserService;
import com.vrv.im.vo.UserVo;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	public long addUser(UserBean userBean) {
		return userMapper.addUser(userBean);
	}

	public UserBean getUserByUserID(long userID) {
		return userMapper.getUserByUserID(userID);
	}

	public List<UserBean> getAllUser() {
		return userMapper.getAllUser();
	}

	@Override
	public Map<Long, Long> addListUser(List<UserVo> userList) {
		Map<Long, Long> map = new HashMap<Long, Long>();
		if (userList != null && userList.size() > 0) {
			for (UserVo v : userList) {
				UserBean ub = new UserBean();
				ub.setPhone(v.getPhone());
				ub.setToken(v.getToken());
				ub.setName(v.getName());
				ub.setOpenId(v.getOpenId());
				userMapper.addUser(ub);
				map.put(v.getRoleMark(), ub.getId());
			}
		}
		return map;
	}

	// @Override
	// public UserBean getUserByTokenID(String token, String openId) {
	// UserBean userBean = new UserBean();
	// userBean.setToken(token);
	// userBean.setOpenId(openId);
	// return userMapper.getUserByTokenID(userBean);
	// }

	@Override
	public UserBean getUserByTokenID(UserBean userBean) {
		if (null != userBean) {
			return userMapper.getUserByTokenID(userBean);
		}
		return null;
	}

	@Override
	public long removeUser(UserBean userBean) {
		return userMapper.delUser(userBean);
	}

	@Override
	public long bindUser(UserBean userBean) {
		UserBean tmpBean = userMapper.getUserByTokenID(userBean);
		if (null == tmpBean) {
			return addUser(userBean);
		} else {
			try {
				long id = tmpBean.getId();
				BeanUtils.copyProperties(tmpBean, userBean);
				tmpBean.setId(id);
				tmpBean.setDelete(Boolean.FALSE);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			return update(tmpBean);
		}
	}

	public long update(UserBean userBean) {
		return userMapper.update(userBean);
	}

}
